import { WebsiteVm } from './../vm/website.vm';
import { AbstractBaseService } from './base.service';
import { WebSiteDomain } from '../model/website.model';

export class WebsiteService extends AbstractBaseService<WebSiteDomain, WebsiteVm> {
    constructor() { 
        super('admin/website');
    }

    async add(obj: WebSiteDomain): Promise<WebSiteDomain> { 
        const url = this.getUrl('setting');
        let vm = this.fromModelToVm(obj);
        vm = this.handleResponse(await this.request.post(url, vm)) as WebsiteVm;
        return this.fromVmToModel(vm);
    }

    async get(): Promise<WebSiteDomain> {
        const url = this.getUrl('setting');
        let vm = this.handleResponse(await this.request.get(url)) as WebsiteVm
        return this.fromVmToModel(vm);
    }

    async cacheRemoveAll(): Promise<boolean> { 
        const url = this.getUrl('cache');
        await this.request.delete(url);
        return true;
    }

    fromVmToModel(vm: WebsiteVm): WebSiteDomain {
        const m = new WebSiteDomain();
        let keys = Object.getOwnPropertyNames(m);
        for (let key in vm) {
            if (keys.indexOf(key) >= 0) {
                (m as any)[key] = (vm as any)[key];
            }
        }
        return m;
    }

    fromModelToVm(model: WebSiteDomain): WebsiteVm {
        const vm = new WebsiteVm();
        let keys = Object.getOwnPropertyNames(vm);
        for (let key in model) {
            if (keys.indexOf(key) >= 0) {
                (vm as any)[key] = (model as any)[key];
            }
        }
        return vm;
    }
}

export const websiteService = new WebsiteService();
export default websiteService;